package com.dtx.controller;

import cn.hutool.core.date.DateUtil;
import com.dtx.anno.ApiLog;
import com.dtx.entity.SysFile;
import com.dtx.msg.ResultMsg;
import com.dtx.service.IFileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;

//@Api(tags = "上传图片接口")
@RestController
@RequestMapping("/beetl/upload")
@Slf4j
public class UploadController {

    @Autowired
    private IFileService fileService;

    @CrossOrigin
    @PostMapping("/file")
    //@ApiOperation("上传图片")
    @ApiLog("上传图片")
    public ResultMsg upload(@RequestParam("file") MultipartFile file) throws IOException {
        log.info("文件上传开始时间为:" + new Date());
        long start = System.currentTimeMillis();
        log.info("===上传文件大小：" + file.getSize());
        if (file.getSize() > 20971520) {
            return ResultMsg.fail("上传附件大小不能超过20M");
        }
        try {
            String fileUrl = "";
            fileUrl = fileService.upload(file.getInputStream(), file.getOriginalFilename());
            SysFile entity = new SysFile();
            entity.setFileUrl(fileUrl);
            entity.setFullUrl(fileUrl);
            entity.setCreateTime(DateUtil.date());
            entity.setIsDelete(0);
            entity.setFileName(fileUrl);
            fileService.insert(entity);
            log.info("文件上传结束时间:"+new Date());
            long end = System.currentTimeMillis();
            long timeCount = end -start;
            log.info("文件上传的总时间为"+timeCount);
            return new ResultMsg(fileUrl);
        } catch (IOException e) {
           throw new IOException();

        }
    }
}
